#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import urllib

from google.appengine.ext import ndb


class Question(ndb.Model):
    author = ndb.StringProperty('a', required=True)
    title = ndb.StringProperty('t', required=True)
    message = ndb.TextProperty('m', required=True)
    date = ndb.DateProperty('d', auto_now_add=True)
    answered = ndb.BooleanProperty('b', default=False)

    @classmethod
    def save(cls, author, title, message):
        question = Question(
            author=author,
            title=title,
            message=message
            )
        return question.put()

    @classmethod
    def get_all(cls):
        return cls.query().order(-cls.date)

    def get_url(self):
        return "/questions/%s/%s" % (self.key.urlsafe(), urllib.quote(self.title.replace(".", "_")))


class Answer(ndb.Model):
    author = ndb.StringProperty('a', required=True)
    message = ndb.TextProperty('m', required=True)
    date = ndb.DateProperty('d', auto_now_add=True)

    @classmethod
    def save(cls, question_url, author, message):

        question_key = ndb.Key(urlsafe=question_url)

        answer = Answer(
            parent=question_key,
            author=author,
            message=message
            )
        answer_key = answer.put()

        question = question_key.get()
        question.answered = True
        question.put()

        return answer_key

    @classmethod
    def from_question(cls, question_key):
        return cls.query(ancestor=question_key).order(cls.date)


def get_questions_no_answered(howmany):
    return Question.query(Question.answered == False).order(-Question.date).fetch(howmany)


def get_question_with_answers(question_url):

    question_key = ndb.Key(urlsafe=question_url)

    return (
        question_key.get(),
        Answer.from_question(question_key)
        )
